<template>
  <div class="pane-account">
    <!-- model绑定account中的属性，这样输入时可以响应式的显示数据 -->
    <el-form :model="account" label-width="50px" size="large" :rules="accountRules" ref="formRef">
      <el-form-item label="帐号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
// 校验规则的函数
import type { FormRules, ElForm } from 'element-plus'
import type { IAccount } from '@/types/index'
// 导入pinia相关
import useLoginStore from '@/store/login/login'
import { localcache } from '@/utils/cache'
const CACHE_NAME = 'name'
const CACHE_PASSWORD = 'password'
const account = reactive<IAccount>({
  name: localcache.getCache(CACHE_NAME) ?? '',
  password: localcache.getCache(CACHE_PASSWORD) ?? ''
})
// 定义校验规则
const accountRules: FormRules = {
  name: [
    { message: '必须输入账号信息', trigger: 'blur', required: true },
    { min: 3, max: 10, message: '请输入3-10位的账号信息', trigger: 'blur' }
  ],
  password: [
    { message: '必须输入密码', trigger: 'blur', required: true },
    { min: 3, max: 10, message: '请输入3-10位的密码', trigger: 'blur' }
  ]
}
// 执行账号的登录逻辑
const formRef = ref<InstanceType<typeof ElForm>>()
const loginStore = useLoginStore()

const loginAction = (isRemPwd: boolean) => {
  // console.log('loginAction')
  formRef.value?.validate((valid) => {
    if (valid) {
      ElMessage.success('验证成功')
      const name = account.name
      const password = account.password
      // 调用pinia中的函数，实现登录
      // 如果登录成功，执行记住密码的操作哟
      loginStore.loginAccountAction({ name, password }).then(() => {
        // 判断是否需要记住密码
        if (isRemPwd) {
          localcache.setCache(CACHE_NAME, name)
          localcache.setCache(CACHE_PASSWORD, password)
        } else {
          // 如果记住密码没有选中，则要把缓存给删除掉
          localcache.delCache(CACHE_NAME)
          localcache.delCache(CACHE_PASSWORD)
        }
      })
    } else {
      console.log('验证失败')
      ElMessage.error('验证失败')
    }
  })
}
// 通过defineExpose将定义的函数向外暴漏
defineExpose({
  loginAction
})
</script>

<style lang="less" scoped>
.pane-account {
  color: red;
}
</style>
